package com.itheima.advice;


import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.MyThreadLocalUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Component
@Aspect
public class MyAspectLog {
    @Pointcut("execution(* com.itheima.service.*.*(..))")
    public void pt() {}

    @Autowired
    private OperateLogMapper operateLogMapper;


    @Around("pt()")
    public Object totalTime(ProceedingJoinPoint pjp) throws Throwable {
        String name = pjp.getSignature().getName();
        if("login".equals(name)){
            Object o = pjp.proceed();
            return o;
        }
        long t1 = System.currentTimeMillis();
        Object o = null;
        try {
            o = pjp.proceed();
        } finally {
            long t2 = System.currentTimeMillis();
            long t3 = t2 - t1;
            Map<String,Object> map = MyThreadLocalUtils.getValue();
            Integer userid = Integer.parseInt(map.get("id").toString());
            OperateLog log = OperateLog.builder()
                    .operateUser(userid)
                    .operateTime(LocalDateTime.now())
                    .className(pjp.getSignature().getDeclaringTypeName())
                    .methodName(name)
                    .methodParams(Arrays.toString(pjp.getArgs()))
                    .returnValue(o==null? "null":o.toString())
                    .costTime(t3)
                    .build();
            operateLogMapper.insert(log);
        }

        return o;
    }
}
